﻿using Caliburn.Micro;
using SS.WPF.Framework.Localization;

namespace SS.WPF.Framework.ValidationRule
{
    using System.Globalization;
    using System.Windows.Controls;
    using System.Text.RegularExpressions;

    public class HostOrIPValidationRule : CommonValidationRule
    {
        /// <summary>
        /// minimum length.
        /// </summary>
        private int _minimumLength = -1;

        /// <summary>
        /// maximum length.
        /// </summary>
        private int _maximumLength = -1;

        private string _eqpName;

        /// <summary>
        /// Gets or sets MinimumLength.
        /// </summary>
        public int MinimumLength
        {
            get { return _minimumLength; }

            set { _minimumLength = value; }
        }

        /// <summary>
        /// Gets or sets MaximumLength.
        /// </summary>
        public int MaximumLength
        {
            get { return _maximumLength; }

            set { _maximumLength = value; }
        }

        public string EquipmentName
        {
            get { return _eqpName; }

            set { _eqpName = value; }
        }
        /// <summary>
        /// validate.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="cultureInfo">
        /// The culture info.
        /// </param>
        /// <returns>
        /// ValidationResult
        /// </returns>
        public override ValidationResult Validate(object value,
                                                  CultureInfo cultureInfo)
        {
            var result = ValidationResult.ValidResult;
            if (!IsEnabled)
            {
                return result;
            }

            var inputString = (value.ToString().Trim() ?? string.Empty);
            if (inputString.Length < this.MinimumLength ||
                (this.MaximumLength > 0 && inputString.Length > this.MaximumLength))
            {
                result = new ValidationResult(false, string.Format((string)IoC.Get<TranslationManager>().Translate("MaxLength"), MaximumLength));
                return result;
            }

            const string validHostnameRegex = @"^([a-z0-9\-\.]*)$";
            if (!Regex.IsMatch(value.ToString().Trim(), validHostnameRegex))
            {
                return new ValidationResult(false, @"[a-z0-9\-\.]*");
            }
            return "-.".Contains(value.ToString().Trim()[0].ToString())
                       ? new ValidationResult(false, @"[a-z0-9\-\.]*")
                       : result;
        }
    }
}
